<template>
  <div ref="editorContainer" class="monaco-editor-container"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as monaco from 'monaco-editor'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  language: {
    type: String,
    default: 'javascript'
  },
  options: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['update:modelValue', 'change'])
const editorContainer = ref(null)
let editor = null

onMounted(() => {
  // 注册 vue 语言支持
  monaco.languages.register({ id: 'vue' })
  
  // 配置 vue 语言的基本设置
  monaco.languages.setMonarchTokensProvider('vue', {
    defaultToken: '',
    tokenizer: {
      root: [
        [/<template>/, 'tag', '@template'],
        [/<script\s*setup>/, 'tag', '@script'],
        [/<style.*>/, 'tag', '@style'],
        [/./, ''],
      ],
      template: [
        [/<\/template>/, 'tag', '@pop'],
        [/./, 'template'],
      ],
      script: [
        [/<\/script>/, 'tag', '@pop'],
        [/./, 'script'],
      ],
      style: [
        [/<\/style>/, 'tag', '@pop'],
        [/./, 'style'],
      ],
    },
  })

  editor = monaco.editor.create(editorContainer.value, {
    value: props.modelValue,
    language: props.language,
    theme: 'vs-dark',
    fontSize: 14,
    minimap: { enabled: false },
    scrollBeyondLastLine: false,
    automaticLayout: true,
    ...props.options
  })

  editor.onDidChangeModelContent(() => {
    const value = editor.getValue()
    emit('update:modelValue', value)
    emit('change', value)
  })
})

watch(() => props.modelValue, (newValue) => {
  if (editor && newValue !== editor.getValue()) {
    editor.setValue(newValue)
  }
})

onBeforeUnmount(() => {
  if (editor) {
    editor.dispose()
  }
})
</script>

<style scoped>
.monaco-editor-container {
  width: 100%;
  height: 100%;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>
